package com.fzu.express.aspect;

import com.alibaba.fastjson.JSON;
import com.fzu.express.annotation.SystemLog;
import com.fzu.express.entity.SysLog;
import com.fzu.express.entity.WebUser;
import com.fzu.express.pojo.RegisterDTO;
import com.fzu.express.pojo.UserVO;
import com.fzu.express.service.SysLogService;
import com.fzu.express.utils.JwtUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @description:
 * @create: 2022-11-05 17:14
 **/

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private SysLogService sysLogService;
    @Pointcut("@annotation(com.fzu.express.annotation.SystemLog)")
    public void pt() {
    }


    @Around("pt()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed;
        try {
            handlerBefore(joinPoint);
            proceed = joinPoint.proceed();
            handleAfter(proceed,joinPoint);
        } finally {
            // 结束后换行
            log.info("===========END============" + System.lineSeparator());
        }
        return proceed;
    }

    private void handleAfter(Object proceed,ProceedingJoinPoint joinPoint) {
        SystemLog systemLog = getSystemLog(joinPoint);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token) && !"null".equals(token)) {
            WebUser user = JwtUtil.getUser(token);
            SysLog sysLog = new SysLog(null, user.getId(), user.getName() + "执行了" + systemLog.businessName() + "操作", null);
            sysLogService.save(sysLog);
        }else if ("登陆".equals(systemLog.businessName())) {
            UserVO userVO = (UserVO) proceed;
            SysLog sysLog = new SysLog(null, userVO.getId(), userVO.getName()+"执行了" + systemLog.businessName() + "操作", null);
            sysLogService.save(sysLog);
        }else if ("注册".equals(systemLog.businessName())) {
            Object[] args = joinPoint.getArgs();
            RegisterDTO registerDTO = (RegisterDTO) args[0];
            SysLog sysLog = new SysLog(null, null, registerDTO.getName()+"执行了" + systemLog.businessName() + "操作", null);
            sysLogService.save(sysLog);
        }
        // 打印出参
        log.info("Response       : {}",JSON.toJSONString(proceed));
    }

    private void handlerBefore(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取被增强方法的注解对象
        SystemLog systemLog = getSystemLog(joinPoint);
//        String token = request.getHeader("token");
//        if (StringUtils.isNotBlank(token) && !"null".equals(token)) {
//            WebUser user = JwtUtil.getUser(token);
//            SysLog sysLog = new SysLog(null, user.getId(), user.getName() + "执行了" + systemLog.businessName() + "操作", null);
//            sysLogService.save(sysLog);
//        }
        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL             : {}",request.getRequestURI());
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 打印描述信息
        log.info("BusinessName   : {}",systemLog.businessName());
        // 打印 Http method
        log.info("HTTP Method    : {}",request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}",joinPoint.getSignature().getDeclaringTypeName(),((MethodSignature) joinPoint.getSignature()).getName());
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));
    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class);
        return systemLog;
    }
}